<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新增巡检计划</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基础信息部分 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="选择开始时间"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡检类型" prop="inspectionType">
              <el-select v-model="form.inspectionType" placeholder="请选择巡检类型" style="width: 100%">
                <el-option label="年检" value="0" />
                <el-option label="季检" value="1" />
                <el-option label="月检" value="2" />
                <el-option label="周检" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="typeId">
              <div v-if="typeOptions.length === 0" style="color: #999;">正在加载设备类型...</div>
              <el-cascader
                v-model="form.typeId"
                :options="typeOptions"
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  value: 'typeId',
                  label: 'typeName',
                  children: 'children',
                  emitPath: false
                }"
                placeholder="请选择设备类型"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="循环周期" prop="cycleValue">
              <el-input-number v-model="form.cycleValue" :min="1" :max="365" placeholder="请输入循环周期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch
                v-model="form.status"
                active-text="启用"
                inactive-text="禁用"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
                :rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 巡检项部分 -->
        <el-divider content-position="left">巡检项</el-divider>
        <el-row>
          <el-col :span="24" style="text-align: right; margin-bottom: 20px;">
            <el-button type="primary" @click="handleSelectItems">选择巡检项</el-button>
          </el-col>
        </el-row>

        <el-table :data="selectedItems" border style="width: 100%">
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="itemName" label="巡检项名称" min-width="120" />
          <el-table-column prop="itemStandard" label="巡检标准" min-width="180" show-overflow-tooltip />
          <el-table-column prop="requireImage" label="图片必传" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.requireImage === '1' ? 'success' : 'info'">
                {{ scope.row.requireImage === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 选择巡检项弹窗 -->
    <el-dialog title="选择巡检项" :visible.sync="selectItemDialog.visible" width="800px" append-to-body>
      <div style="margin-bottom: 20px;">
        <el-input
          placeholder="请输入关键词搜索"
          v-model="selectItemDialog.queryParams.keyword"
          style="width: 200px;"
          clearable
          @keyup.enter.native="handleItemSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleItemSearch"></el-button>
        </el-input>
        <el-button type="primary" style="float: right;" @click="handleAddItem">新增巡检项</el-button>
        <el-button style="float: right; margin-right: 10px;" @click="handleItemReset">重置</el-button>
      </div>

      <el-table v-loading="selectItemDialog.loading" :data="selectItemDialog.items" @selection-change="handleItemSelectionChange" border>
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="itemName" label="巡检项名称" min-width="120" />
        <el-table-column prop="itemStandard" label="巡检标准" min-width="180" show-overflow-tooltip />
        <el-table-column prop="requireImage" label="图片必传" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.requireImage === '1' ? 'success' : 'info'">
              {{ scope.row.requireImage === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="selectItemDialog.total > 0"
        :total="selectItemDialog.total"
        :page.sync="selectItemDialog.queryParams.pageNum"
        :limit.sync="selectItemDialog.queryParams.pageSize"
        @pagination="getItemList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="selectItemDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectItems">确定</el-button>
      </div>
    </el-dialog>

    <!-- 巡检项新增/编辑弹窗 -->
    <el-dialog :title="itemDialog.title" :visible.sync="itemDialog.visible" width="500px" append-to-body>
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="100px">
        <el-form-item label="巡检项名称" prop="itemName">
          <el-input v-model="itemForm.itemName" placeholder="请输入巡检项名称" />
        </el-form-item>
        <el-form-item label="巡检标准" prop="itemStandard">
          <el-input v-model="itemForm.itemStandard" type="textarea" :rows="3" placeholder="请输入巡检标准" />
        </el-form-item>
        <el-form-item label="图片必传" prop="requireImage">
          <el-switch v-model="itemForm.requireImage" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="itemDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitItemForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addInspectionPlan } from "@/api/sb/inspectionPlan";
import { getTreeselect } from '@/api/sb/equipmentType';
import { listInspectionItem, addInspectionItem } from '@/api/sb/inspectionItem';
import Pagination from '@/components/Pagination';

export default {
  name: "AddInspectionPlan",
  components: { Pagination },
  data() {
    return {
      // 表单参数
      form: {
        planName: null,
        startDate: null,
        inspectionType: "0",
        typeId: null,
        cycleValue: 7,
        status: "1", // 默认启用
        remark: null,
        items: []  // 选中的巡检项ID列表
      },
      // 表单校验
      rules: {
        planName: [
          { required: true, message: "请输入计划名称", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "请选择开始时间", trigger: "change" }
        ],
        inspectionType: [
          { required: true, message: "请选择巡检类型", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "请选择设备类型", trigger: "change" }
        ],
        cycleValue: [
          { required: true, message: "请输入循环周期", trigger: "blur" }
        ]
      },
      // 设备类型选项
      typeOptions: [],
      // 选中的巡检项列表
      selectedItems: [],
      // 选择巡检项弹窗
      selectItemDialog: {
        visible: false,
        loading: false,
        items: [],
        total: 0,
        selectedIds: [],
        selectedRows: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          keyword: ''
        }
      },
      // 巡检项弹窗
      itemDialog: {
        visible: false,
        title: '新增巡检项'
      },
      // 巡检项表单
      itemForm: {
        itemName: '',
        itemStandard: '',
        requireImage: '0'
      },
      // 巡检项表单校验
      itemRules: {
        itemName: [
          { required: true, message: '巡检项名称不能为空', trigger: 'blur' }
        ],
        itemStandard: [
          { required: true, message: '巡检标准不能为空', trigger: 'blur' }
        ]
      },
      // 调试模式
      debugMode: false
    };
  },
  created() {
    this.getTypeTree();
  },
  methods: {
    /** 获取设备类型树 */
    getTypeTree() {
      console.log('开始获取设备类型树');
      getTreeselect().then(response => {
        console.log('设备类型树数据:', response);
        this.typeOptions = this.handleTreeData(response.data);
      });
    },
    
    /** 处理设备类型树数据 */
    handleTreeData(data) {
      // 打印接收到的数据格式
      console.log('处理前的设备类型树数据:', data);
      
      // 确保树结构中的各节点都有正确的typeId值
      return data.map(item => {
            const node = {
          typeId: item.typeId,
          value: item.typeId, // 确保使用正确的ID值作为选择值
          label: item.typeName || item.label
            };
            
        if (item.children && item.children.length > 0) {
          node.children = this.handleTreeData(item.children);
            }
            
            return node;
      });
    },
    /** 打开选择巡检项弹窗 */
    handleSelectItems() {
      this.selectItemDialog.visible = true;
      this.getItemList();
    },
    /** 获取巡检项列表 */
    getItemList() {
      this.selectItemDialog.loading = true;
      listInspectionItem(this.selectItemDialog.queryParams).then(response => {
        this.selectItemDialog.items = response.rows;
        this.selectItemDialog.total = response.total;
        this.selectItemDialog.loading = false;

        // 恢复已选项的选中状态
        this.$nextTick(() => {
          if (this.selectedItems.length > 0) {
            const refTable = this.$refs.multipleTable;
            if (refTable) {
              this.selectedItems.forEach(row => {
                const targetRow = this.selectItemDialog.items.find(item => item.itemId === row.itemId);
                if (targetRow) {
                  refTable.toggleRowSelection(targetRow, true);
                }
              });
            }
          }
        });
      });
    },
    /** 搜索巡检项 */
    handleItemSearch() {
      this.selectItemDialog.queryParams.pageNum = 1;
      this.getItemList();
    },
    /** 重置巡检项查询 */
    handleItemReset() {
      this.selectItemDialog.queryParams.keyword = '';
      this.selectItemDialog.queryParams.pageNum = 1;
      this.getItemList();
    },
    /** 巡检项选择事件 */
    handleItemSelectionChange(selection) {
      this.selectItemDialog.selectedRows = selection;
    },
    /** 确认选择巡检项 */
    confirmSelectItems() {
      // 将新选择的项合并到已选列表中，避免重复
      if (this.selectItemDialog.selectedRows.length > 0) {
        const newSelectedItems = [...this.selectedItems];
        this.selectItemDialog.selectedRows.forEach(item => {
          if (!newSelectedItems.some(existing => existing.itemId === item.itemId)) {
            newSelectedItems.push(item);
          }
        });
        this.selectedItems = newSelectedItems;
      }
      this.selectItemDialog.visible = false;
    },
    /** 删除选中的巡检项 */
    handleDeleteItem(index) {
      this.selectedItems.splice(index, 1);
    },
    /** 新增巡检项按钮操作 */
    handleAddItem() {
      this.itemDialog.title = '新增巡检项';
      this.resetItemForm();
      this.itemDialog.visible = true;
    },
    /** 重置巡检项表单 */
    resetItemForm() {
      this.itemForm = {
        itemName: '',
        itemStandard: '',
        requireImage: '0'
      };
      this.$nextTick(() => {
        this.$refs.itemForm && this.$refs.itemForm.resetFields();
      });
    },
    /** 提交巡检项表单 */
    submitItemForm() {
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.itemForm));
          
          // 添加必要字段
          item.configId = 1; // 使用默认配置ID
          item.createBy = this.$store.getters.name;
          item.createTime = new Date();
          
          console.log('提交新巡检项数据:', item);
          
          // 新增巡检项到数据库
          addInspectionItem(item).then(response => {
            console.log('新增巡检项响应:', response);
            
            // 获取返回的ID，优先使用响应数据中的ID
            const itemId = response.data && response.data.itemId ? 
              response.data.itemId : 
              (response.itemId || new Date().getTime()); // 如果没有ID，使用时间戳作为临时ID
            
            // 添加新巡检项到选中列表
            const newItem = {
              itemId: itemId,
              itemName: this.itemForm.itemName,
              itemStandard: this.itemForm.itemStandard,
              requireImage: this.itemForm.requireImage,
              configId: 1
            };
            
            console.log('添加到选中列表的巡检项:', newItem);
            this.selectedItems.push(newItem);
            
            this.itemDialog.visible = false;
            this.$modal.msgSuccess('新增巡检项成功');
            this.getItemList(); // 刷新巡检项列表
          }).catch(error => {
            console.error('新增巡检项失败:', error);
            this.$modal.msgError('新增巡检项失败: ' + (error.message || '未知错误'));
          });
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.$router.push("/sb/Inspection-plan");
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.selectedItems.length === 0) {
            this.$modal.msgError('请至少选择一个巡检项');
            return;
          }
          
          // 获取当前用户名
          const userName = this.$store.getters.name;
          const currentTime = new Date();
          
          // 准备提交数据
          const data = {
            ...this.form,
            typeId: this.form.typeId, // 直接使用typeId，不做额外映射
            configId: this.form.typeId, // 将typeId同时也用作configId
            cycleType: this.form.inspectionType, // 将inspectionType映射为cycleType
            createBy: userName,
            createTime: currentTime,
            updateBy: userName, // 添加updateBy字段
            updateTime: currentTime, // 添加updateTime字段
            planCode: 'XJJH' + this.parseTime(new Date(), '{y}{m}{d}') + this.getRandomCode(), // 自动生成计划编号
            items: this.selectedItems.map(item => item.itemId),
            status: "1", // 确保状态值正确设置
            isDelete: "0" // 确保删除标志正确设置
          };
          
          // 确保必要的日期字段都已设置
          if (!data.startDate) {
            data.startDate = this.parseTime(new Date(), 'yyyy-MM-dd');
          }
          
          if (!data.endDate) {
            // 默认设置一年后为结束日期
            const endDate = new Date();
            endDate.setFullYear(endDate.getFullYear() + 1);
            data.endDate = this.parseTime(endDate, 'yyyy-MM-dd');
          }
          
          // 确保移除inspectionDate字段，该字段在数据库表中不存在
          delete data.inspectionDate;
          
          console.log('提交巡检计划数据:', data);
          
          addInspectionPlan(data).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$router.push("/sb/Inspection-plan");
          }).catch(error => {
            console.error('新增巡检计划失败:', error);
            this.$modal.msgError('新增巡检计划失败: ' + (error.message || '未知错误'));
          });
        }
      });
    },

    // 获取随机编码
    getRandomCode() {
      return Math.floor(Math.random() * 900 + 100).toString(); // 生成100-999的随机数
    },

    // 解析时间
    parseTime(time, c) {
      const d = new Date(time);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      if (c) {
        return c.replace('{y}', year)
                .replace('{m}', month)
                .replace('{d}', day);
      }
      return year + month + day;
    }
  }
};
</script> 